package cn.edu.scnu.pay.controller;

import cn.edu.scnu.annotation.IgnoreToken;
import cn.edu.scnu.pay.config.AlipayClientConfig;
import cn.edu.scnu.pay.service.AlipayService;
import cn.edu.scnu.pojo.AlipayBean;
import cn.edu.scnu.vo.OrderStatus;
import cn.edu.scnu.vo.ResultCode;
import cn.edu.scnu.vo.SysResult;
import com.alipay.api.internal.util.AlipaySignature;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Api
@RestController
public class AlipayController {

    @Autowired
    private AlipayClientConfig alipayClientConfig;

    @Autowired
    private AlipayService alipayService;

    /**
     * 支付宝网页支付
     *
     * @param alipayBean
     * @return
     */
//    @PostMapping("/alipay/pay")
//    @ApiOperation(value = "/alipay/pay", notes = "支付宝扫码支付")
//    @ApiImplicitParam(name = "alipayBean", value = "订单信息", dataType = "cn.edu.scnu.pojo.AlipayBean", required = true, paramType = "body")
//    public SysResult pay(@RequestBody AlipayBean alipayBean) {
//        return alipayService.pay(alipayBean);
//    }
    @IgnoreToken
    @PostMapping("/alipay/pay")
    @ApiOperation(value = "/alipay/pay", notes = "支付宝扫码支付")
    @ApiImplicitParam(name = "alipayBean", value = "订单信息", dataType = "cn.edu.scnu.pojo.AlipayBean", required = true, paramType = "body")
    public String pay(AlipayBean alipayBean) {
        return alipayService.pay(alipayBean);
    }

    @IgnoreToken
    @PostMapping("/alipay/refund")
    @ApiOperation(value = "/alipay/refund", notes = "订单退款")
    @ApiImplicitParam(name = "alipayBean", value = "订单信息", dataType = "cn.edu.scnu.pojo.AlipayBean", required = true, paramType = "body")
    public SysResult refund(AlipayBean alipayBean) {
        System.out.println(alipayBean.getOut_trade_no());
        return alipayService.refund(alipayBean);
    }

    @IgnoreToken
    @GetMapping("/alipay/success")
    @ApiOperation(value = "/alipay/success", notes = "支付成功之后返回数据")
    public SysResult alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付宝同步通知页面");
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayClientConfig.getPublicKey(), alipayClientConfig.getCharset(), alipayClientConfig.getSignType());
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");


            // 修改订单状态为支付成功，已付款; 同时新增支付流水

            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println("* 订单号: " + out_trade_no);
            System.out.println("* 支付宝交易号: " + trade_no);
            System.out.println("* 实付金额: " + total_amount);
            System.out.println("***************************************************************");

            //设置返回的数据
        } else {
            System.out.println("验签失败");
            return SysResult.build(ResultCode.FAIL, "fail", null);
        }
        return SysResult.ok();
    }

    @IgnoreToken
    @RequestMapping(value = "/alipay/notify")
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        System.out.println("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            /*valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");*/
            params.put(name, valueStr);
        }

        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayClientConfig.getPublicKey(), alipayClientConfig.getCharset(), alipayClientConfig.getSignType());
        //验证成功
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                alipayService.updateOrderStatus(out_trade_no, OrderStatus.TRADE_FINISHED);
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改订单状态，改为 支付成功，已付款; 同时新增支付流水


                System.out.println("********************** 支付成功(支付宝异步通知) **********************");
                System.out.println("* 订单号: " + out_trade_no);
                System.out.println("* 支付宝交易号: " + trade_no);
                System.out.println("* 实付金额: " + total_amount);
                System.out.println("***************************************************************");
                alipayService.updateOrderStatus(out_trade_no, OrderStatus.TRADE_SUCCESS);
            }
            System.out.println("支付成功");
        } else {//验证失败
            System.out.println("验签失败");
            return "fail";
        }
        return "success";
    }
}
